<template>
    <div class="video-box">
        <video ref="videoRef" class="video" :poster="poster" :loop="loop" :muted="muted" :volume="app.volume"
               @click="playing = false" @mouseenter="startTimer"></video>
        <div class="scrubber">
            <Scrubber v-model="currentTime" :max="duration" :secondary="endBuffer">
                <template #default="{ position, pendingValue }">
                    <div class="time" :style="{ left: position}">
                        {{ formatDuration(pendingValue) }}
                    </div>
                </template>
            </Scrubber>
        </div>
    </div>
</template>

<script setup lang="ts">
import {useMediaControls} from "@vueuse/core";
import useStore from "@/store";

const {app} = useStore();

const emit = defineEmits(['upIndex']);

const props = defineProps({
    videoUrl: {
        type: String,
        default: ''
    },
    poster: {
        type: String,
        default: ''
    },
    index: {
        type: Number,
        default: 0
    }
});

const videoRef = ref<HTMLVideoElement>();

const data = reactive({
    loop: false,
});

const {loop} = toRefs(data);

const controls = useMediaControls(videoRef, {
    src: {
        src: props.videoUrl,
        type: 'video/webm',
    },
});

const {playing, buffered, currentTime, duration, muted} = controls;

const endBuffer = computed(() => buffered.value.length > 0 ? buffered.value[buffered.value.length - 1][1] : 0);

let timerId: ReturnType<typeof setTimeout> | null = null;

/**
 * 鼠标悬浮2s开始播放视频
 */
const startTimer = () => {
    emit('upIndex', props.index);
    timerId = setTimeout(() => {
        playing.value = true;
    }, 2000);
}

const formatDuration = (seconds: number) => {
    return new Date(1000 * seconds).toISOString().slice(14, 19)
}

const clearTimer = () => {
    if (timerId) {
        clearTimeout(timerId);
        timerId = null;
    }
    playing.value = false;
    currentTime.value = 0;
}

defineExpose({startTimer, clearTimer});
</script>

<style scoped lang="scss">
.video-box {
  position: relative;
  width: 100%;
  height: 100%;

  .video {
    width: 100%;
    height: 4.4rem;
    object-fit: cover;
    overflow: hidden;
    transition: all 0.5s;
  }

  .scrubber {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 0.15rem;
    transition: all 0.5s;

    .time {
      position: absolute;
      bottom: 0.15rem;
      color: var(--text-color);
    }
  }
}
</style>